<template>
  <div class="consumer-page activity-list-page">
    <el-breadcrumb class="breadcrumb page-title" separator="/">
      <el-breadcrumb-item :to="{ path: '/propertyIndex'}">Property</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/propertyNew'}">New</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="container-padding">
      <!--serchBox-->
      <div class="search-box">
        <el-form :inline="true" label-position="top" :model="form" size="mini" ref="form" :rules="rules"
                 class="demo-ruleForm main-search-box">
          <!--Status-->
          <el-row>
            <el-form-item label="Status" style="margin-right: 10px">
              <el-select style="width: 140px" v-model="form.status" placeholder="">
                <el-option v-for="i in statusOption" :key="i.value" :label="i.label" :value="i.value"></el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <!--english name-->
          <el-row>
            <el-form-item label="Eng Name" style="width: 250px;" class="name-require" prop="name">
              <el-input v-model="form.name" placeholder=""></el-input>
            </el-form-item>
          </el-row>
          <!--Mm name-->
          <el-row>
            <el-form-item label="Mm Name" style="width: 250px;">
              <el-input v-model="form.nameMm" placeholder=""></el-input>
            </el-form-item>
          </el-row>
          <!--category-->
          <el-row>
            <!-- 级联菜单 -->
            <!--第一级菜单-->
            <el-form-item label="Category1" style="width: 200px;margin-right: 10px" prop="firstCategory">
              <el-select style="width: 200px" v-model="form.firstCategory" @change="getSecondaryData">
                <el-option v-for="i in categoryData" :key="i.id" :label="i.name" :value="i.name"></el-option>
              </el-select>
            </el-form-item>
            <!--第二级菜单-->
            <el-form-item label="Category2" style="width: 200px;margin-right: 10px"
                          v-if="secondaryData.length>0||form.secondaryCategory" prop="secondaryCategory">
              <el-select style="width: 200px" v-model="form.secondaryCategory" @change="getThirdData"
              >
                <el-option v-for="i in secondaryData" :key="i.id" :label="i.name" :value="i.name"></el-option>
              </el-select>
            </el-form-item>
            <!--第三级菜单-->
            <el-form-item label="Category3" style="width: 200px;margin-right: 10px"
                          v-if="thirdData.length>0||form.thirdCategory"
                          prop="thirdCategory">
              <el-select style="width: 200px" v-model="form.thirdCategory" @change="getNewId">
                <el-option v-for="i in thirdData" :key="i.id" :label="i.name" :value="i.name"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="margin-top: 37px;">
              <el-button @click="addCategory" type="success" style="width:80px">Add</el-button>
            </el-form-item>
          </el-row>
          <!--categoryList-->
          <div style="margin:10px 0;">
            <el-row :gutter="12">
              <el-col :span="12" v-for="(item,index) in categoryList">
                <div class="card-wraper">
                  <el-card shadow="hover">
                    {{item.categoryName}}
                  </el-card>
                  <i class="el-icon-delete delete-icon" @click="deleteItem(index)"></i>
                </div>
              </el-col>
            </el-row>
          </div>
          <!--search-->
          <el-form-item style="margin-top: 37px">
            <el-button @click="$router.back(-1)" type="info" style="width:80px;">Cancel</el-button>
          </el-form-item>
          <el-form-item style="margin-top: 37px;">
            <el-button @click="propertyAdd" type="success" style="width:80px">Save</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>

  import {addNewProperty, getCategory} from '../../api/guc_api.js'
  import Qs from "qs";

  export default {
    name: 'propertyNew',
    data() {
      return {
        categoryData: [],
        secondaryData: [],
        thirdData: [],
        categoryId: '',
        categoryName: '',
        id: '',
        categoryList: [],
        form: {
          status: '1',
          name: '',
          nameMm: '',
          firstCategory: '',
          secondaryCategory: '',
          thirdCategory: '',
        },
        statusOption: [
          {
            label: 'Active',
            value: '1'
          },
          {
            label: 'Deleted',
            value: '0'
          }
        ],
        //校验
        rules: {
          name: [
            {
              validator: (rule, value, callback) => {
                if (value === "") {
                  callback(new Error("please enter user name"));
                }
                else {
                  callback();
                }
              },
              trigger: "blur"
            }
          ],
          firstCategory: [
            {required: true, message: 'please select category1', trigger: 'change'}
          ],
          secondaryCategory: [
            {required: true, message: 'please select category2', trigger: 'change'}
          ],
          thirdCategory: [
            {required: true, message: 'please select category3', trigger: 'change'}
          ]
        },
      }
    },
    methods: {
      //下面是对category菜单的操作。。。。。。。。。。。。。。。。。。。。。。。。。
      // 获取二级菜单
      getSecondaryData() {
        this.form.secondaryCategory = ''
        this.secondaryData = []
        this.form.thirdCategory = ''
        this.thirdData = []
        let index
        index = this.categoryData.findIndex((item) => {
          return item.name === this.form.firstCategory
        })
        this.secondaryData = this.categoryData[index].children
        if (this.form.firstCategory) {
          this.categoryData.forEach((item) => {
            if (item.name === this.form.firstCategory) {
              this.categoryId = item.id
              this.categoryName = item.name
            }
          })
        }
      },
      // 获取三级菜单
      getThirdData() {
        this.form.thirdCategory = ''
        this.thirdData = []
        let index
        index = this.secondaryData.findIndex((item) => {
          return item.name === this.form.secondaryCategory
        })
        this.thirdData = this.secondaryData[index].children
        if (this.form.secondaryCategory) {
          this.secondaryData.forEach((item) => {
            if (item.name === this.form.secondaryCategory) {
              this.categoryId = item.id
              this.categoryName += '/' + item.name
            }
          })
        }
      },
      //获取新的catId
      getNewId() {
        if (this.form.thirdCategory) {
          this.thirdData.forEach((item) => {
            if (item.name === this.form.thirdCategory) {
              this.categoryId = item.id
              this.categoryName += '/' + item.name
            }
          })
        }
      },
      //增加category
      addCategory() {
        // 然后验证表单信息
        this.$refs['form'].validate((valid) => {
          if (!valid) {
            this.messageToastErr('Wrong Submit')
            return false
          }
          else {
            let newCategory = {
              id: this.categoryId,
              categoryName: this.categoryName
            }
            //要校验一下这个分类是否已经存在了，如果已经存在就不能再添加了，并弹出提示
            let ifAdd = true
            this.categoryList.forEach((item => {
              if (item.id == this.categoryId) {
                ifAdd = false
                return
              }
            }))
            if (ifAdd) {
              this.categoryList.push(newCategory)
            }
            else {
              this.messageToastErr('Category has already exist!')
            }
            //添加完成后重置category数据
            this.form.secondaryCategory = ''
            this.secondaryData = []
            this.form.thirdCategory = ''
            this.thirdData = []
          }
        })
      },
      //下面是对属性的操作。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
      //动态获取category
      getNewCategory() {
        getCategory()
          .then(res => {
            let data = JSON.parse(res.data.object)
            this.categoryData = data
          })
          .catch(err => {
            console.log(err)
          })
      },
      //删除某个category
      deleteItem(index) {
        this.$confirm('Are you sure to delete?', 'Notice', {
          confirmButtonText: 'Yes',
          cancelButtonText: 'No',
          type: 'warning'
        }).then(() => {
          this.categoryList.splice(index, 1)
          this.$message({
            type: 'success',
            message: 'Delete Success!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: 'Delete Cancel'
          });
        });
      },
      //提交新增属性
      propertyAdd() {
        // 然后验证表单信息
        this.$refs['form'].validate((valid) => {
          if (!valid) {
            this.messageToastErr('Wrong Submit')
            return false
          }
          else {
            //要确认用户已经执行了add操作
            if (!this.categoryList.length > 0) {
              this.messageToastErr('Please add category first,categories at least have one')
            }
            else {
              //对categoryList处理一下，只要id，不要name
              let newArr = []
              this.categoryList.forEach(item => {
                newArr.push(item.id)
              })
              let params = {
                status: this.form.status,
                name: this.$translateLang(this.form.name || '', 'zawgyiTounicode') || '',
                nameMm: this.$translateLang(this.form.nameMm || '', 'zawgyiTounicode') || '',
                categoryIds: JSON.stringify(newArr),
              }
              params = Qs.stringify(params)
              addNewProperty(params)
                .then(res => {
                  if (res.data.errorID == 0) {
                    this.messageToastSuccess('Save Success')
                    this.$router.push('/propertyIndex')
                  }
                  else {
                    this.messageToastErr(res.data.message)
                  }
                })
                .catch(err => {
                  console.log(err)
                })
            }
          }
        })
      },
      // message alert 用于前端错误提示信息
      messageToastErr(msg) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 5000,
          type: 'error'
        })
      },
      //成功消息提示
      messageToastSuccess(msg) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 5000,
          type: 'success'
        })
      },
    },
    mounted() {
      this.getNewCategory()
    }
  }
</script>


<style>
  .page-title {
    padding: 20px 40px;
    border-bottom: 1px solid #e6e6e6;
    font-size: 20px !important;
  }

  .breadcrumb {
    margin-bottom: 20px;
  }

  .page-title {
    padding: 20px 40px;
    border-bottom: 1px solid #e6e6e6;
    font-size: 20px;
  }

  .search-box {
    position: relative;
    border-bottom: 1px solid #eee;
  }

  .container-padding {
    padding: 0 40px;
  }

  .card-wraper {
    position: relative;
    margin: 5px 0;
  }

  .card-wraper .delete-icon {
    position: absolute;
    right: 5px;
    top: 5px;
    font-size: 18px;
    color: red;
    cursor: pointer;
  }

  .name-require::before {
    content: "*";
    color: #f56c6c;
    margin-right: 4px;
    position: relative;
    top: 20px;
    left: -8px;
  }
</style>
